alter proc spLapDoanhThuTheoNgay (@maNH int, @ngayTongKet Datetime)
as
begin
	DECLARE @tongTien float
	
	select @tongTien = sum(ThanhTien) from HoaDonBan where MaNH = @maNH and day(NgayLapHD) = day(@ngayTongKet)
		and month(NgayLapHD) = month(@ngayTongKet) and year(NgayLapHD) = year(@ngayTongKet)
	if(@tongTien is null)
		set @tongTien = 0
	if ((select count(*) from DoanhThu where MaNH = 1 and day(NgayTongKet) = day(@ngayTongKet)
		and month(NgayTongKet) = month(@ngayTongKet) and year(NgayTongKet) = year(@ngayTongKet))> 0)
	begin -- da ton tai chi cap nhat gia tri cac hoa don trong ngay
		update DoanhThu
			set TongTienBan = @tongTien
		where MaNH = @maNH and day(NgayTongKet) = day(@ngayTongKet)
		and month(NgayTongKet) = month(@ngayTongKet) and year(NgayTongKet) = year(@ngayTongKet)
	end
	else -- chua ton tai, them moi tong gia tri cac hoa don trong ngay
	begin
		insert into DoanhThu (TongTienBan, NgayTongKet, MaNH)
		values (@tongTien,@ngayTongKet,@maNH)
	end
end